<%@ page contentType="text/html; charset=UTF-8"%>
<%@ include file="/jsp/common/common.jsp"%>
<html>  
<head>  
    <title><%=IConstant.PROGRAEM_TITLE%></title>
    		<style>
			.icon_edit {
			background-image: url(<%=contextPath%>/images/edit.gif)!important;
			}
		
			.icon_check {
				background-image: url(<%=contextPath%>/images/accept.png)!important;
			}
			
			.icon_user {
				background-image: url(<%=contextPath%>/images/user_suit.png)!important;
			}
 		</style>
    	<script type="text/javascript"> 

    	var checking = false;
    	var flagSQ;
 		var contentTabs;
 		var formBase;
 		var treeMenu;
 		var storeMenu;
 		var layout;
 		var gridUser;
 		var treeOrgan;
 		var storeGrid;
 		var storeOrgan;
 		var treeRole;
 		
 		var tempRoleId2;
 		var tempRoleId3;
 		
 		
        Ext.onReady(function(){
        	tab1Build();
        });
 
         var tab1Build = function(){
			
			// 角色列表
			treeRole = new Ext.tree.TreePanel({
            	id:'treeRole',
                loader: new Ext.tree.TreeLoader({url : 'role!getRoleList.do'}),
                root:new Ext.tree.AsyncTreeNode({
                	id:'rootRole',
                	text:'',
                	leaf:false
            	}),
                border:false,
                rootVisible:false,
        		useArrows:true,
        		autoScroll:true,
		        containerScroll:true,
		        listeners:{"click":function(node){ 
					var activTab = contentTabs.getItem("role1");  
					contentTabs.setActiveTab(activTab); 
					Ext.Ajax.request({
						method :'POST',
						url :'role!find.do',
						params : {id :node.id},
						success : function(response, options) { 
							var obj = Ext.decode(response.responseText);
							// 页面控件赋值
							formBase.getForm().findField("entity.id").setValue(obj["id"]);
							//formBase.getForm().findField("entity.rolecode").setValue(obj["rolecode"]);
							//formBase.getForm().findField("entity.rolelevel").setValue(obj["rolelevel"]);
							formBase.getForm().findField("entity.nameen").setValue(obj["nameen"]);
							formBase.getForm().findField("entity.name").setValue(obj["name"]);
							formBase.getForm().findField("entity.notes").setValue(obj["notes"]);
							//Ext .getCmp("entity.rolecode").getEl().dom.readOnly = true; 
							
						},
						failure : function() {
							Ext.MessageBox.alert('提示 ', '提取数据失败！');
						}
					});
                }}
            });
			
			// 基本信息工具栏
			var toolbar1 = new Ext.Toolbar({
 				items: [ {	id :'addDicButton',
							text :'增加',
							cls:'x-btn-text-icon',
				            icon:'<%=contextPath%>/images/add.gif',
							tooltip :'添加一个角色',
							handler:addRole,
							hidden:<%=session.getAttribute("btn_add_display") != null || "1".equals(session.getAttribute("SESSION_ISADMIN")) ? false:true%>
						}, '-', {
							id :'saveDicButton',
							text :'保存',
				            cls:'x-btn-text-icon',
				            icon:'<%=contextPath%>/images/save.gif',
							tooltip :'保存角色',
							handler:formSubmit,
							hidden:<%=session.getAttribute("btn_save_display") != null || "1".equals(session.getAttribute("SESSION_ISADMIN")) ? false:true%>
						}, '-', {
							id :'deleteDicButton',
							text :'删除',
				            cls:'x-btn-text-icon',
				            icon:'<%=contextPath%>/images/delete.gif',
							tooltip :'删除所选角色',
							handler:deleteRole,
							hidden:<%=session.getAttribute("btn_delete_display") != null || "1".equals(session.getAttribute("SESSION_ISADMIN")) ? false:true%>
						} ]
		   			});
		   			
		   	// 基本信息form 
       		formBase = new Ext.FormPanel({
				frame :true,
				labelAlign :'right',
				waitMsgTarget :true,
				autoScroll :true,
				method :'POST',
				url :'role!save.do',
				items : [{
					xtype :'textfield',
					fieldLabel :'*名称英文缩写',
					name :'entity.nameen',
					allowBlank :false,
					maxLength :20,
					width :200,
					style:'ime-mode:disabled;'
				},{
					xtype :'textfield',
					fieldLabel :'*名称',
					name :'entity.name',
					allowBlank :false,
					maxLength :100,
					width :200
				}, {
            		xtype:'textarea',
					fieldLabel:'角色描述',
           			name:'entity.notes',
            		width:459,
            		height:100,
            		enableFont:false,
            		maxLength:100
				}, {
					xtype :'hidden',//hidden
					name :'entity.id',
					value :'0'
				}, {
					xtype :'hidden',
					name :'checkedMenuID'
				}, {
					xtype :'hidden',
					name :'organCode'
				}]
			});
			
			tab3firstBuild();
			
			// tab页设置
            contentTabs = new Ext.TabPanel({   
                activeTab: 0,   
                height:600,   
                border: true,   
                deferredRender: false,   
                tabPosition: 'top',
		        listeners:{"tabchange":function(Tabs, tab){ 
					setActiveTab(tab);
                }},
                items: [{
                	id:'role1',
                    title:"基本信息",
                    iconCls:'icon_edit',
                    autoScroll: true,   
                    icon:'<%=contextPath%>/images/delete.gif',
                    items:[toolbar1,formBase]   
                },{   
                    title:"应用授权",
                    id:'role2',
                    iconCls:'icon_check',
                    autoScroll: true  
                 	//items:[toolbar2,treeMenu]
                },{ 
                	id:'role3',  
                    title:"人员授权", 
                    iconCls:"icon_user", 
                    layout:'border',  
                    items:[treeOrgan, new Ext.Panel({ 
            								region:'center',
                    						items:[gridUser]
            						})]
                }]   
            });   

         	// layout
            layout = new Ext.Viewport({   
                layout: 'border',   
                margins:'5 0 5 5',   
                items: [   
                 {  region: 'west',
                    collapsible: true,   
                    split: true,   
                    width: 230,    
                    minSize: 175,   
                    maxSize: 400,   
                    title: '角色列表',   
                    layout: {   
                        type: 'accordion'
                    },
                    items:[treeRole]
                },{ region: 'center',   
                    title: '角色管理',
                    height:800,
                    layout:'fit',
                    items:[contentTabs]  
                }]   
            }); 
            // 
            tempRoleId2 = "0";
            tempRoleId3 = "0";

       };
       			
       // 第二个面板
       var tab2Build = function () {

		if (treeMenu == undefined || treeMenu.root.firstChild == null) {

			treeMenu = new Ext.tree.TreePanel({
				id:'treeMenu',
	    		root:new Ext.tree.TreeNode({
	    			id:'rootMenu',
	    			text:'<%=IConstant.PROGRAEM_TITLE%>应用管理',
	    			leaf:false,
	    			checked:false,
	    			expanded:true
				}),
	    		border:false,
				useArrows:true,
				autoScroll:true,
				containerScroll: true,
				store:storeMenu
			});
			
			storeMenu = new Ext.data.Store({
        		proxy:new Ext.data.HttpProxy({url:'role!getMenu.do'}),
        		reader:new Ext.data.JsonReader({},['id','text','qtip','parentID','checked']),
        		autoLoad:true
    		});

    		storeMenu.on('load',function(store,records){
    			if (records != null && records != "") {
					for (var i=0; i<records.length; i++){
	       				var n = new Ext.tree.TreeNode({
                			id:records[i].data.id,
                			text:records[i].data.text,
                			checked:(records[i].data.checked == "" ? false : records[i].data.checked),
                			leaf:true
						});
						try {
	       				// 第一层菜单时
	       				if (records[i].data.parentID == "0") {
            				treeMenu.root.appendChild(n);
            			// 下级菜单
	       				} else {//window.alert(records[i].data.parentID);
	       					treeMenu.getNodeById(records[i].data.parentID).leaf = false;
	       					treeMenu.getNodeById(records[i].data.parentID).appendChild(n);
	       				}

						} catch(e) {
							alert("加载" + records[i].data.parentID + "出错");
						}
   					}
				}
				 //treeMenu.getRootNode().expand(true,false);
				 //treeMenu.expandAll();
    		});
    		
   	 		// 将树放入角色layout
            contentTabs.items.get(1).add(treeMenu);		
			contentTabs.items.get(1).doLayout();

		} else {
		
			// 如果角色变化时
			if (tempRoleId2 != formBase.getForm().findField("entity.id").getValue()) {
				tempRoleId2 = formBase.getForm().findField("entity.id").getValue();
				storeMenu.reload();
			}
		}
		
	    /* 单击 */     
	    treeMenu.on("click",function(node) {
	        
			if (node.isLeaf() == undefined || !node.isLeaf()){
	   
				if (!node.isExpanded()) {
					node.expand();		
				} else {
				    node.collapse();
				}              
			}
				         
	     });
		
  		/* 加载数据前操作 */
    	storeMenu.on("beforeload", function(s,o) {
    		// 清除所有结点
    		while(treeMenu.root.childNodes.length>0) {
    			for (var i=0;i<treeMenu.root.childNodes.length;i++) {
    				treeMenu.root.removeChild(treeMenu.root.childNodes[i]);
    			}
    		}
    		// 给root放上checkbox值
    		if (formBase.getForm().findField("entity.id").getValue() == "0") {
    			treeMenu.root.ui.toggleCheck(false);
    		} else {
    			treeMenu.root.ui.toggleCheck(true);
    		}
    		s.baseParams.id = formBase.getForm().findField("entity.id").getValue();
   	 	});
   	 		
		// checkbox触发事件
		treeMenu.on('checkchange', function(node,checked) { 
	
			if(checking){ 
				return false;
			}
				
			checking = true;
			// 选中的话
			if(node.ui.isChecked()){
				checkChildren(node,true);
				checkParent(node);
			
			// 没选中
			} else {
				checkChildren(node,false);
				uncheckParent(node);
			}
		
			checking = false;
		});
		
		treeMenu.expand(true);
		
      }
       
       // 初始化的时候先放个空
       var tab3firstBuild = function() {
       	
       		var xg = Ext.grid;
       
       		var sm = new xg.CheckboxSelectionModel();
       
       		// 加载分页数据
			storeGrid = new Ext.data.Store( {
				proxy :new Ext.data.HttpProxy( {
					url :"userList!getListExt.do"//?limit=10&start=0"// +'!list'
				}),
				reader :new Ext.data.JsonReader( {
					root :'result',
					totalProperty :'totalCount',
					// id : 'id',
					fields : [ 'id', 'loginId', 'name','userCount','isadmin']
				}),
				//autoLoad:true,
				remoteSort :false
			});
	
			// 创建GridPanel
			gridUser = new Ext.grid.GridPanel({
				titleVisible:false,
				store :storeGrid,
				frame:true,
        		cm: new xg.ColumnModel({
            		defaults: {
                		width: 120,
                		sortable: true
            		},
            		columns: [
            			new xg.RowNumberer(),
                		sm,
    					{
    						id:'loginId',
							header :"序号",
							width :50,
							dataIndex :'id',
							sortable :true,
							hidden :true
						}, {
							header :"授权状态",
							width :150,
							dataIndex :'userCount',
							sortable :true,
							renderer:function(v) {
								if (v == 0) {
									return "<font color='green'>未授权</font>";
								} else {
									return "<font color='red'>已授权</font>";
								}
							},
							align:'center'
						}, {
							header :"用户编号",
							width :150,
							dataIndex :'loginId',
							sortable :true
						}, {
							header :"用户名称",
							width :150,
							dataIndex :'name',
							sortable :true
						}, {
						header :"是否管理员",
							width :150,
							dataIndex :'isadmin',
							sortable :true,
							renderer:function(v) {
								if (v == 0) {
									return "<font color='green'>否</font>";
								} else {
									return "<font color='red'>是</font>";
								}
							}
						}]
				}),
				sm: sm,
				loadMask : {msg :'载入中,请稍候...'},
				viewConfig:{forceFit:true},
				tbar : [
				{
					id :'1',
					text :'授权',
					cls:'x-btn-text-icon',
            		icon:'<%=contextPath%>/images/user_add.png',
					tooltip :'授权选中用户',
					handler:function() {flagSQ= '1' , setRole()},
					hidden:<%=session.getAttribute("btn_role_display") != null || "1".equals(session.getAttribute("SESSION_ISADMIN")) ? false:true%>
				}, '-', {
					id :'2',
					text :'取消授权',
            		cls:'x-btn-text-icon',
            		icon:'<%=contextPath%>/images/user_delete.gif',
					tooltip :'取消选中用户授权',
					handler:function() {flagSQ= '0' , setRole()},
					hidden:<%=session.getAttribute("btn_unrole_display") != null || "1".equals(session.getAttribute("SESSION_ISADMIN")) ? false:true%>
				}],
				bbar :new Ext.PagingToolbar( {
					id:'b',
					pageSize :10,
					store :storeGrid,
					displayInfo :true,
					displayMsg :'显示 {0} - {1} 共 {2} 条',
					emptyMsg :"没有数据显示！",
					beforePageText :"页码 ",
					afterPageText :"共 {0} 页",
					firstText :"首页",
					lastText :"末页",
					nextText :"下一页",
					prevText :"上一页",
					refreshText :"刷新"
				})
			});

			/* 生成Ttee,放到tree Div里面 */
			treeOrgan = new Ext.tree.TreePanel({
                        id:"mytree",
                        region: 'west',    
                        rootVisible:false,
                        root : new Ext.tree.TreeNode({   
                    			id : "rootOrgan", 
                    			draggable:false, 
                    			singleClickExpand:true, 
                    			text : "<%=IConstant.PROGRAEM_TITLE%>"
	 						}),  
                        width :230,   
				        useArrows:true,
				        autoScroll:true,
				        animate:true,
				        containerScroll:true,
				        listeners:{"click":function(node){ 
				        	
							formBase.getForm().findField("organCode").setValue(node.attributes.qtip);
							storeGrid.baseParams.organCode = node.attributes.qtip;
							storeGrid.baseParams.roleID = formBase.getForm().findField("entity.id").getValue();
							storeGrid.reload({params:{start:0,limit:10}}); 
                    	}}
				});	
       }
       
		// 第三个面板
		var tab3Build = function () {
		
		  if (treeOrgan == null || treeOrgan.root.firstChild == null) {
       		
			storeOrgan = new Ext.data.Store({
        		proxy:new Ext.data.HttpProxy({url:'organ!getOrgan.do'}),
        		reader:new Ext.data.JsonReader({},['id','text','qtip','parentId']),
        		autoLoad:true,
        		listeners:{"load":function(store,records){
        							if (records != null && records != "") {
										for (var i=0; i<records.length; i++){
	       									var n = new Ext.tree.TreeNode({
                								id:records[i].data.id,
                								text:records[i].data.text,
                								qtip:records[i].data.qtip,
                								leaf:true
											});
   
	       									// 第一层菜单时
	       									if (records[i].data.parentId == "0") {
            									treeOrgan.root.appendChild(n);
            								// 下级菜单
	       									} else {
	       										treeOrgan.getNodeById(records[i].data.parentId).leaf = false;
	       										treeOrgan.getNodeById(records[i].data.parentId).appendChild(n);
	       									}
   										}
   										
   										treeOrgan.expandAll();
   										
   										// 设置分页数据
										formBase.getForm().findField("organCode").setValue(treeOrgan.root.firstChild.attributes.qtip);
										storeGrid.baseParams.organCode = treeOrgan.root.firstChild.attributes.qtip;
										storeGrid.baseParams.roleID = formBase.getForm().findField("entity.id").getValue();
										storeGrid.reload({params:{start:0,limit:10}}); 
       
									} 
                }}
    		});
    		
    		contentTabs.items.get(2).doLayout();
    		
    	} else {
    	
    			// 如果角色变化时
			if (tempRoleId3 != formBase.getForm().findField("entity.id").getValue()) {
				tempRoleId3 = formBase.getForm().findField("entity.id").getValue();
				storeGrid.baseParams.organCode = treeOrgan.root.firstChild.attributes.qtip;
				storeGrid.baseParams.roleID = formBase.getForm().findField("entity.id").getValue();
				storeGrid.reload({params:{start:0,limit:10}}); 
			}
    	} 
 	}

	// 子结点处理
	function checkChildren(node, checked)
	{
		//for(var i =0;i<node.childNodes.length;i++) {
		//	node.childNodes[i].ui.toggleCheck(checked);
		//	checkChildren(node.childNodes[i], checked);
		//}
       node.attributes.checked = checked;
       node.ui.toggleCheck(checked);
       node.eachChild(function(child){
         checkChildren(child,checked);
       }); 
	}

	// 选中所有父结点
	function checkParent(node) {
		if(node.parentNode == null){
			return false;
		}
		node.parentNode.ui.toggleCheck(true);
		checkParent(node.parentNode);
	}

	// 取消所有父结点
	function uncheckParent(node) {
		if(node.parentNode == null) {
			return false;
		}
		var blCheck = true;
		for(var i =0;i<node.parentNode.childNodes.length;i++) {
			if(node.parentNode.childNodes[i].ui.isChecked()) {
				blCheck = false;
			}
		}
		if(blCheck) {
			node.parentNode.ui.toggleCheck(false);
			uncheckParent(node.parentNode);
		}
	}
	
	// 授权 0： 取消授权；1：授权
	function setRole() {
	
		if (!formBase.form.isValid()) {
			Ext.MessageBox.alert('提示', '人员授权时请先选择一个角色信息。');
			var activTab = contentTabs.getItem("role1");  
			contentTabs.setActiveTab(activTab); 
			return false;
		}
		var m = "确认要授权的用户？";
		if (flagSQ == "0") {
			m = "确认要取消授权的用户？";
		}
		if (gridUser.getSelectionModel().getSelections().length > 0)
			Ext.MessageBox.confirm('消息', m, toSetRole);
		else
			Ext.MessageBox.alert('警告', '最少需要选择一个用户!');
	};

	// 确定要授权后执行事件
	function toSetRole(btn) {

		if (btn == 'yes') {
		
			if (gridUser.getSelectionModel().hasSelection()) {
				var ids = '';
				var records = gridUser.getSelectionModel().getSelections();
				for ( var i = 0; i < records.length; i++) {
				
					if (i == 0) {
						ids = records[0].data["id"];
					} else {
						ids += ',' + records[i].data["id"];
					}
				}
				Ext.Ajax.request( {
					method :'POST',
					url :'role!saveUserRole.do',
					params : {
						checkedMenuID :ids,
						flagSQ:flagSQ,
						id:formBase.getForm().findField("entity.id").getValue()
					},
					success : function(response) {
						Ext.MessageBox.alert('提示', Ext.decode(response.responseText).msg);
						storeGrid.baseParams.organCode = formBase.getForm().findField("organCode").getValue();
						storeGrid.reload();
					},
					failure : function() {
						Ext.MessageBox.alert('提示', '操作失败！');
						storeGrid.baseParams.organCode = formBase.getForm().findField("organCode").getValue();
						storeGrid.reload();
					}
				});
			}
		}
	};

	// 新建时先清空	   			
	function addRole() {
		formBase.getForm().findField("entity.id").setValue("0");
		formBase.getForm().findField("entity.nameen").setValue("");
		formBase.getForm().findField("entity.name").setValue("");
		formBase.getForm().findField("entity.notes").setValue("");
		formBase.getForm().findField("checkedMenuID").setValue("");
		if (treeMenu != undefined) {
			setCheckMenuUncheck(treeMenu.root);
		}
		
		//Ext .getCmp("entity.rolecode").getEl().dom.readOnly = false; 

		//alert(Ext.get('entity.rolecode').el.dom.readOnly);
	}
	
	// 保存
	function formSubmit() {
	
		if (!formBase.form.isValid()) {
			Ext.MessageBox.alert('提示', '保存时基本信息、应用授权必须输入。');
				var activTab = contentTabs.getItem("role1");  
				contentTabs.setActiveTab(activTab); 
				return false;
		}
		
		if (treeMenu == undefined) {
			tab2Build();
		}
		
		// 保存前过滤复选框选中的树结点
		formBase.getForm().findField("checkedMenuID").setValue(treeMenu.getChecked("id", treeMenu.root));
		formBase.getForm().findField("checkedMenuID").setValue(formBase.getForm().findField("checkedMenuID").getValue().replace("rootMenu,",""));

		if (formBase.getForm().findField("checkedMenuID").getValue() == "") {
			Ext.MessageBox.alert('提示', '请选择该角色的应用授权。');
			var activTab = contentTabs.getItem("role2");  
			contentTabs.setActiveTab(activTab);
			return false;
		} 

		
		
					formBase.getForm().submit({
						waitMsg :'保存中...',
						success : function(form, action) {
							Ext.MessageBox.alert('提示', action.result.msg);
							Ext.getCmp("treeRole").root.reload();
							
							var activTab = contentTabs.getItem("role1");  
							contentTabs.setActiveTab(activTab);
							addRole();
						},
						failure : function() {
							Ext.MessageBox.alert('提示', '保存失败。');
						}
				
					});
	

	};
	
	// 删除角色
	function deleteRole() {
		if (formBase.getForm().findField("entity.id").getValue() == "0") {
			Ext.MessageBox.alert('提示', '请选择要删除的角色。');
			return false;
		}
		
		Ext.MessageBox.confirm('消息', "删除角色时同时删除该角色的用户授权，确认要删除选中角色？", toDeleteRole);
	}

	// 确定要删除后执行事件
	function toDeleteRole(btn) {

		if (btn == 'yes') {

		Ext.Ajax.request({
			method :'POST',
			url :'role!delete.do',
			params : {id:formBase.getForm().findField("entity.id").getValue()},
			success : function(response, options) {
				var obj = Ext.decode(response.responseText);
				Ext.MessageBox.alert('提示', obj["msg"]);
				addRole();
				if(Ext.getCmp("treeRole").root.childNodes.length == 1) {
					Ext.getCmp("treeRole").root.removeChild(Ext.getCmp("treeRole").root.childNodes[0]);
				} else {
					Ext.getCmp("treeRole").root.reload();
				}

			},
			failure : function(response, options) {
				Ext.MessageBox.alert('提示 ', '删除失败。');
			}
		});
		
		}
	
	}
	
	// 取消所有结点
	function setCheckMenuUncheck(node) {
       node.attributes.checked = false;
       node.ui.toggleCheck(false);
       node.eachChild(function(child){
         setCheckMenuUncheck(child,false);
       }); 
       // 回新建状态
		tempRoleId2 = "0";
		tempRoleId3 = "0";
     }
	

	
	// tab变化时触发事件
	function setActiveTab(tab) {
	
		if (tab.id == "role2") {
			tab2Build();
		} else if (tab.id == "role3") {
			tab3Build();
		}
	}
    </script>  
</head>  
  
<body>  
      <div id="Container">  
          <div id="ToolBar"></div>  
          <div id="Content"></div>  
          <div id="StatuBar"></div>  
      </div>  
</body>  
</html>


